﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiscreteMath
{
	public class ConfigurationConverter : JsonConverter
	{
		private static Type ConfigurationType = typeof(string);
		public override bool CanConvert(Type objectType)
		{
			return objectType == ConfigurationType;
		}
		 
		public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
		{
			// Read the key
			reader.Read();
			string key = reader.Value.ToString();
			string[] split = key.Replace("State: ", string.Empty).Replace(" Letter: ", string.Empty).Split(',');
			string state = split[0];
			string letter = split[1];
			if (letter.Length != 1)
			{
				throw new ArgumentException(string.Format("The letter may only be a single character, instead it is: {0}", letter));
			}
			return new Configuration(new State(state), letter.First());
		}

		public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
		{
			writer.WriteRaw(value.ToString());
		}
	}
}
